package com.hnust.root.web.controller;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.hnust.root.common.base.exception.BusinessException;
import com.hnust.root.common.base.exception.DBException;
import com.hnust.root.common.base.response.BaseRestController;
import com.hnust.root.common.base.response.BaseResult;
import com.hnust.root.common.model.LoginModel;
import com.hnust.root.common.model.ManagerInfo;
import com.hnust.root.common.util.JWTUtil;
import com.hnust.root.dao.entity.domain.Manager;
import com.hnust.root.service.auth.ManagerInfoService;
import com.hnust.root.service.auth.ManagerService;
import com.hnust.root.web.annotation.SysLog;
import com.hnust.root.web.shiro.ShiroKit;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 登录接口类
 */
@RestController
@RequestMapping("/auth")
public class AuthController extends BaseRestController {

    private static final Log LOGGER = LogFactory.get();

    @Value("jwt.secret")
    private String defaultSecret;

    @Resource
    private ManagerInfoService managerInfoService;

    @Autowired
    private ManagerService managerService;


    @PostMapping("/login")
    @SysLog(modelName = "鉴权模块",operation = "登录",desc = "用户请求登录")
    public BaseResult<String> login(@RequestBody LoginModel loginModel) throws BusinessException {
        LOGGER.info("用户 ： {} 请求登录,登录时间：{}", loginModel.getUsername(), LocalDateTime.now());
        String username = loginModel.getUsername();
        String password = loginModel.getPassword();
        ManagerInfo managerInfo = managerInfoService.findByUsername(username);

        if (managerInfo != null) {
            //随机数盐
            String salt = managerInfo.getSalt();
            //原密码加密（通过username + salt作为盐）
            String encodedPassword = ShiroKit.md5(password, username + salt);
            if (managerInfo.getPassword().equals(encodedPassword)) {

                LOGGER.info("用户登录成功，此用户信息为： {}", managerInfo);
                return fillSuccessData(JWTUtil.sign(username, encodedPassword,managerInfo.getId()));
            } else {
                throw new UnauthorizedException();
            }
        } else {
            throw new BusinessException("用户名不存在！");
        }
    }

    @PostMapping("/register")
    public BaseResult<Manager> register(@RequestBody Manager manager) throws BusinessException {
        manager = managerService.addManager(manager);
        if (manager == null) {
            throw new DBException();
        } else {
            return fillSuccessData(manager);
        }
    }
}
